<template>
  <a-card class="min-h-[68px] rounded my-[10px]" :body-style="{ padding: '0px 10px', minHeight: '400px' }"
    :bordered="false">
    <!-- 头部返回列表功能 -->
    <template #extra>
      <a-button class="border-none" icon="rollback" @click="rollback">{{
        $t("app.setting.themecolor.rr99")
      }}</a-button>
    </template>
    <!-- 正文头部 -->
    <div slot="title">
      <a-space>
        <div class="ty"></div>
        {{ $t("user.verification-code.required1115661105720") }}
      </a-space>
    </div>
    <!-- 头部导航+查看RPA详情 -->
    <div style="margin: 30px 10px 0px 20px">
      <div style="display: flex; justify-content: space-between">
        <!-- 查看详情 -->
        <div style="
              margin-left: 20px;
              margin-top: -6px;
              right: 0;
              position: absolute;
              margin-right: 20px;
            ">
          <rpaDetail :rpaDetailId="id" :lang="lang" />
        </div>
      </div>
    </div>

    <!-- 主列表 -->
    <div class="card-right">
      <a-row>
        <a-space class="mb-[15px]">
          <div class="tags"></div>
          {{ $t("user.verification-code.required1115661105760") }}
        </a-space>
        <a-row type="flex">
          <a-col :span="12">
            <a-table ref="table" size="middle" class="h-full overflow-x-auto" :pagination="dpiaSimpleEstimatePagination"
              :dataSource="dpiaSimpleEstimateLists" :rowKey="(record) => record.Id">
              <a-table-column key="DpiaChapterTitle" data-index="DpiaChapterTitle">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required1115661105761")
                }}</span>
              </a-table-column>
              <a-table-column key="DpiaChapterDcoRemark" data-index="DpiaChapterDcoRemark">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required1115661105762")
                }}</span>
                <span key="DpiaChapterDcoRemark" slot-scope="text">
                  <span v-html="text"></span>
                </span>
              </a-table-column>
            </a-table>
          </a-col>
          <a-col style="
                margin-left: 20px;
                height: 200px;
                overflow-y: scroll;
                padding-top: 5px;
              " :span="11">
            <a-timeline>
              <a-timeline-item v-for="item in transferList" :key="item.Id">
                <div>
                  {{ item.DpiaCommentsDCO + item.DpiaCommentsCreatetime }}
                </div>
                <div>
                  {{ $t("user.verification-code.required1115661105763") }}：{{
                    item.DpiaCommentsTypeStr
                  }}
                </div>
                <div>
                  <span>{{
                    $t("user.verification-code.required111566181")
                  }}</span>{{ item.DpiaCommentsInfo ? item.DpiaCommentsInfo : "无" }}
                </div>
              </a-timeline-item>
            </a-timeline>
          </a-col>
        </a-row>

      </a-row>
    </div>

    <!-- 下方按钮 -->
    <div :style="{
      position: 'fixed',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '20px 16px',
      background: '#fff',
      textAlign: 'center',
      zIndex: 1,
    }">
      <a-button @click="rollback()" style="margin-right: 20px">{{
        $t("app.setting.themecolor.rr")
      }}</a-button>
      <!-- 生成DPIA评估报告 -->
      <a-button type="primary" :loading="buttonLoading" @click="savePush()" :disabled="state == 'see'"
        style="margin-right: 20px">
        {{ $t("user.verification-code.required1115661105767") }}
      </a-button>
      <a-button type="primary" @click="returnChapter()" v-if="state !== 'see'">
        {{ $t("user.verification-code.returnchapter") }}
      </a-button>
    </div>
  </a-card>
</template>
  
<script>
import {
  dpiaQuestionChapterLists,
  dpiaQuestionInfo,
  dpiaSimpleAnswer,
  dpiaQuestionTopic,
  dpiaQuestionAnswerCreate,
  dpiaQuestionChangeStatus,
  dpiaSimpleAction,
  dpiaDcoRemarkInfo,
  dpiaDcoRemarkInfoUpdate,
  dpiaDcoTransfer,
  dpiaDcoBackoff,
  dpiaRiskLists,
  getItemsChapterRemark,
  transferDetails,
  DpiaUpload,
  dpiaChangeState,
  dpiaSeeSimpleAction,
  createSettime,
  getNextTime,
  dpiaCompleteAssessment,
  isWithdraw,
} from "@/api/dpia/form";
import Readio from "./readio.vue";
import Checkbox from "./checkbox.vue";
import Esitory from "./esitory.vue";
import Four from "./four.vue";
import RpaDetail from "./components/rpaDetail.vue";
import CreateAction from "./components/createAction.vue";
import CreateRisk from "./components/createRisk.vue";
import { userQuery } from "@/api/common/form";
import { ristDelAction } from "@/api/risk/form";
import moment from "moment";
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import axios from "axios";
import qs from "qs";

export default {
  components: {
    Readio,
    Checkbox,
    Esitory,
    Four,
    RpaDetail,
    CreateAction, // 创建Action
    CreateRisk, // 创建RISK
  },
  watch: {
    dcoRemark: async function () {
      try {
        // 更新创建备注
        await dpiaDcoRemarkInfoUpdate({
          DpiaChapterDcoRemark: this.dcoRemark,
          DpiaQid: this.id,
          DpiaChapterId: this.chapterId,
        });
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
  },
  data() {
    return {
      buttonLoading: false,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          if (selectedRowKeys.length > 0) {
            this.riskButtom = false;
            this.actionIdGroups = selectedRowKeys;
            this.actionDataGroups = selectedRows;
            this.rowSelection.selectedRowKeys = [
              ...this.selectedRowKeys,
              ...selectedRowKeys,
            ];
          } else {
            this.rowSelection.selectedRowKeys = [...this.selectedRowKeys];
            this.riskButtom = true;
          }
        },
        getCheckboxProps: (record) => ({
          props: {
            checked: record.RiskId !== 0,
            disabled: record.RiskId !== 0, // Column configuration not to be checked
          },
        }),
        selectedRowKeys: [],
      },
      // DCO评估结果
      dcoRemark: undefined,
      dco: undefined,
      // DCO列表
      userList: [],
      // DCO按钮
      dcoButtom: false,
      disabledDate: "",

      current: "",
      value: "",
      visible: false,

      // DCO backoff的状态
      dcoBackoffVisible: false,

      // 配置分页
      dpiaSimpleAnswerPagination: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      dpiaSimpleActionPagination: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      dpiaSimpleRiskPagination: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      dpiaSimpleEstimatePagination: {
        page: 1,
        pageSize: 5,
        total: 0,
        // onChange: this.onchange, // 页码改变时的回调函数
      },

      // 左侧的章节列表
      chapterLists: [],

      // 基础答题信息
      questionnaireInfo: {},

      // 问题和答案数据
      dpiaQuestionTopicAnswer: {},

      // 问卷ID
      id: "",

      // 当前选中章节ID
      chapterId: "",

      // 获取用户问题答案
      dpiaQuestionUserAnswer: {},

      // 当前题型
      topicType: 0,

      // 是否结束
      finishStatus: 0,

      // 已答题的结果
      dpiaQuestionUserLastAnswer: "",

      // 答题章节内容
      dpiaSimpleAnswerLists: [],

      // Action列表
      dpiaSimpleActionLists: [],

      // 评估意见列表
      dpiaSimpleEstimateLists: [],

      // 选中的ActionID列表
      actionIdGroups: [],
      // 选中的ActionData列表
      actionDataGroups: [],
      //RISK列表
      dpiaSimpleRiskLists: [],

      //创建风险按钮状态
      riskButtom: true,
      //转办详情列表
      transferList: [],
      // 整体评估/查看see
      state: "",
      //下次评估时间
      DpiaNextTime: null,
      // 当前语言
      lang: "zh-EN",
      exportLoading: false,
      ifLoading: false,
      selectedRowKeys: [],
    };
  },
  created() {
    this.init();
  },
  mounted() {
    const nowLang =  localStorage.getItem("lang").includes("zh-EN")
      if( nowLang ) {
        this.lang = 'zh-EN'
      }else{
        this.lang = 'zh-CN'
      }
      window.addEventListener('setItemEvent',  (e)=> {
        if (e.key == 'lang') {
          this.lang = JSON.parse(e.value)
        }
    })
  },
  methods: {
    async delAction(record) {
      try {
        // 传过来的id直接请求删除api
        await ristDelAction({ Id: record.Id });
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
        // 重新初始化列表刷新数据
        this.actions();
      } catch (error) {
        this.$message.error(error);
      } finally {
      }
    },
    async setActionToRisk() {
      // 创建RISk
      this.$refs.createRisk.open(this.actionIdGroups, this.actionDataGroups);
    },
    onChange(value, dateString) {
      console.log("Selected Time: ", value);
      console.log("Formatted Selected Time: ", dateString);
    },
    async onOk(value) {
      const Time = moment(value).format("YYYY-MM-DD HH:mm:ss");
      const { data } = await createSettime({ DpiaNextTime: Time, Id: this.id });
    },
    /*
     * 完成评估
     * @param state
     * @returns {Promise<void>}
     */
     async savePush(state) {

      // 修改状态
      if (state != 'see') {
        await dpiaChangeState({
          Id: this.id,
          DpiaStatus: 4,
        })
        this.$message.success(
          this.$t('user.verification-code.required111566110577308')
        )
        await this.$router.push({ path: '/dpia/service' })
      }

      if (state === 'see') this.exportLoading = true
      else this.buttonLoading = true

      try {
        // 交换意见已达成

        const { data: chinaReport } = await DpiaUpload({ Id: this.id, lang: 1 })
        const { data: englishReport } = await DpiaUpload({ Id: this.id, lang: 2 })

        this.reportUrlC = chinaReport.dpiaReport[0].DpiaReportAddress
        this.reportUrlE = englishReport.dpiaReport[0].DpiaReportAddress

        console.log(' this.reportUrl111', this.reportUrlC);
        console.log(' this.reportUrl222', this.reportUrlE);

        if (this.pia) {

          if (this.lang === 'zh-CN') {
            sessionStorage.setItem('report', this.reportUrlC)
            this.$router.push({
              path: '/dpia/report',
            })
          } else if (this.lang === 'zh-EN') {
            sessionStorage.setItem('report', this.reportUrlE)
            this.$router.push({
              path: '/dpia/report',
            })
          }
        }

        // const { data: chinaReport } = await axios({
        //   // 用axios发送post请求
        //   method: 'post',
        //   url: process.env.VUE_APP_BASE_API + '/v1/dpia/report/upload', // 请求地址
        //   data: qs.stringify({ Id: this.id, lang: 1 }),
        //   responseType: 'blob', // 表明返回服务器返回的数据类型
        //   headers: {
        //     'Content-Type':
        //       'application/x-www-form-urlencoded; application/octet-stream',
        //     token: storage.get(ACCESS_TOKEN),
        //     tokens: storage.get('bmwToken') || '',
        //     env: process.env.NODE_ENV,
        //   },
        // })

        // const { data: englishReport } = await axios({
        //   // 用axios发送post请求
        //   method: 'post',
        //   url: process.env.VUE_APP_BASE_API + '/v1/dpia/report/upload', // 请求地址
        //   data: qs.stringify({ Id: this.id, lang: 2 }),
        //   responseType: 'blob', // 表明返回服务器返回的数据类型
        //   headers: {
        //     'Content-Type':
        //       'application/x-www-form-urlencoded; application/octet-stream',
        //     token: storage.get(ACCESS_TOKEN),
        //     tokens: storage.get('bmwToken') || '',
        //     env: process.env.NODE_ENV,
        //   },
        // })

        // if (this.pia) {
        // 下载中文报告
        // await this.dumpPdf(chinaReport)
        // 下载英文报告
        // await this.dumpPdf(englishReport)
        // } else {
        // }

      } catch (error) {
        this.$message.error(error)
        console.log(error)
      }
      this.buttonLoading = false
      this.exportLoading = false
      },


    async dumpPdf(content) {
      const blob = new Blob([content], {
        // 下载的文件格式自己在这边更改type的值就好了
        type: "application/pdf",
      });
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a");
        elink.download = moment() + ".pdf";
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, filename);
      }
    },
    editActions(id) {
      // 编辑action
      this.$refs.createAction.open(id, "edit", true);
    },
    createActions() {
      // 创建Action
      this.$refs.createAction.open();
    },
    async dcoBackoffShow() {
      this.dcoBackoffVisible = true;
    },
    async dcoBackoff() {
      // DCO退回
      try {
        await dpiaDcoBackoff({ id: this.id });
        this.$router.push({ path: "/dpia/service" });
        this.$message.success(
          this.$t("user.verification-code.required111566110577272")
        );

        this.dcoBackoffVisible = false;
      } catch (error) {
        this.$message.error(error);
        console.log(error);
      }
    },
    async changeChapter(items) {
      try {
        for (var i = 0; i < this.chapterLists.length; i++) {
          this.chapterLists[i].check = false;
        }
        // 获取DCO评估结论
        const { data: remarkInfo } = await dpiaDcoRemarkInfo({
          DpiaQid: this.id,
          DpiaChapterId: items.id,
        });
        this.dcoRemark = remarkInfo.DpiaChapterDcoRemark;
        this.chapterId = items.id;

        items.check = true;
        // 默认获取第一章节
        const { data: dpiaSimpleAnswerObject } = await dpiaSimpleAnswer({
          id: this.id,
          DpiaChapterId: items.id,
          lang: this.lang === "zh-CN" ? 0 : 1,
        });
        const { Page, PageSize, Total, Lists } = dpiaSimpleAnswerObject;

        this.dpiaSimpleAnswerLists = Lists;
        this.dpiaSimpleAnswerPagination = {
          page: Page,
          pageSize: PageSize,
          total: Total,
        };
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async transfer() {
      // DCO转办
      try {
        if (this.dco == undefined) {
          this.$message.error(
            this.$t("user.verification-code.required111566110577268")
          );
          return;
        }

        var dcoName = "";
        for (var i = 0; i < this.userList.length; i++) {
          if (this.userList[i].value == this.dco) {
            dcoName = this.userList[i].label;
          }
        }
        await dpiaDcoTransfer({
          id: this.id,
          DpiaDco: dcoName,
          DpiaDcoUserId: this.dco,
        });
        this.$message.success(
          this.$t("user.verification-code.required111566110577269")
        );
        this.visible = false;
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async transferShow() {
      // 转办的弹窗
      this.visible = true;
      // 获取用户列表下拉
      const { data: userList } = await userQuery(1);

      this.userList = userList;
    },
    // async onchange(e) {
    //   console.log(e);
    //   const { data: dpiaSimpleActionObject } = await getItemsChapterRemark({
    //     Id: this.id,
    //     e,
    //     pageSize: 5,
    //   });
    //   const { Page, PageSize, Total, Lists } = dpiaSimpleActionObject;
    //   this.dpiaSimpleEstimateLists = Lists;
    // },
    async actions() {
      // 获取关联的Action
      try {
        this.riskButtom = true;
        const { page, pageSize } = this.dpiaSimpleActionPagination;
        // 默认获取第一章节

        const { data: dpiaSimpleActionObject } = await dpiaSimpleAction({
          Id: this.id,
          page,
          pageSize,
        });
        const { Page, PageSize, Total, Lists } = dpiaSimpleActionObject;
        this.dpiaSimpleActionLists = Lists;
        this.dpiaSimpleActionPagination = {
          page: Page,
          pageSize: PageSize,
          total: Total,
        };
        // 多选
        const newSelectedKeys = Lists
          .filter(item => item.RiskId !== 0)
          .map(item => item.Id);
        this.rowSelection.selectedRowKeys = Array.from(new Set([...this.rowSelection.selectedRowKeys, ...newSelectedKeys]));
        this.selectedRowKeys = newSelectedKeys
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async estimates() {
      // 获取评估意见列表
      try {
        const { page, pageSize } = this.dpiaSimpleEstimatePagination;
        // 默认获取第一章节
        const { data: dpiaSimpleEstimateObject } = await getItemsChapterRemark({
          Id: this.id,
          page,
          pageSize: 100,
        });
        const { Page, PageSize, Total, Lists } = dpiaSimpleEstimateObject;
        //获取转办详情
        const { data } = await transferDetails({ Id: this.id });
        this.transferList = data;
        this.dpiaSimpleEstimateLists = Lists;
        var tempLists = [];
        for (var i = 0; i < this.dpiaSimpleEstimateLists.length; i++) {
          if (this.dpiaSimpleEstimateLists[i].DpiaChapterDcoRemark) {
            this.dpiaSimpleEstimateLists[i].DpiaChapterDcoRemark =
              this.dpiaSimpleEstimateLists[i].DpiaChapterDcoRemark.join("<br>");
            tempLists.push(this.dpiaSimpleEstimateLists[i]);
          }
        }
        this.dpiaSimpleEstimateLists = tempLists;
        console.log("dpiaSimpleEstimateLists:", this.dpiaSimpleEstimateLists);

        this.dpiaSimpleEstimatePagination = {
          page: Page,
          pageSize: 5,
          total: Total,
        };
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async risks() {
      // 获取关联的RISK
      try {
        this.riskButtom = true;
        const { page, pageSize } = this.dpiaSimpleRiskPagination;
        // 默认获取第一章节
        const { data: dpiaSimpleRiskObject } = await dpiaRiskLists({
          Id: this.id,
          page,
          pageSize,
        });
        console.log(dpiaSimpleRiskObject);
        const { Page, PageSize, Total, Lists } = dpiaSimpleRiskObject;
        this.dpiaSimpleRiskLists = Lists;
        this.dpiaSimpleRiskPagination = {
          page: Page,
          pageSize: PageSize,
          total: Total,
        };
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async init() {
      try {
        // 初始化题库
        this.id = this.$route.query.id;

        //初始化页面状态
        const state = this.$route.query.state;
        //区分是整体评估还是查看
        this.state = state;

        // 获取初步评估Action
        await this.actions();

        // 获取RISK
        await this.risks();

        // 获取评估的意见
        await this.estimates();

        // // 基础信息查询
        // const { data: questionnaireInfo } = await dpiaQuestionInfo({
        //   id: this.id,
        // });
        // this.questionnaireInfo = questionnaireInfo;

        //获取下次评估时间
        const { data: DpiaNextTime } = await getNextTime({ Id: this.id });
        this.DpiaNextTime = DpiaNextTime.DpiaNextTime
          ? DpiaNextTime.DpiaNextTime
          : null;
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async pageInit(obj) {
      this.dpiaQuestionUserAnswer = obj;
      try {
        // 获取答案
        if (this.dpiaQuestionUserAnswer != {}) {
          // 把答题的结果拿到
          await dpiaQuestionAnswerCreate({
            DpiaChapterId: this.dpiaQuestionUserAnswer.chapter,
            DpiaQid: this.id,
            DpiaChapterTopicId: this.dpiaQuestionUserAnswer.topic,
            DpiaChapterTopicAnswer: encodeURIComponent(this.dpiaQuestionUserAnswer.answer),
            DpiaChapterTopicType: this.dpiaQuestionTopicAnswer.topic.type,
          });

          // 清空答案
          this.dpiaQuestionUserAnswer = {};
        }
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async showModal() {
      this.visible = true;
      // 获取用户列表下拉
      const { data: userList } = await userQuery(1);

      this.userList = userList;
    },
    async handleOk(e) {
      // 交卷
      if (this.dco == undefined) {
        this.$message.error(
          this.$t("user.verification-code.required111566110577268")
        );
        return;
      }
      try {
        await dpiaQuestionChangeStatus({
          Id: this.id,
          DpiaStatus: 2,
          DpiaDcoUserId: this.dco,
        });
        this.$message.success(
          this.$t("user.verification-code.required111566110577270")
        );
      } catch (error) {
        this.$message.error(error);
      }

      this.topicShow();
      this.visible = false;
      // 开启那个结果页
      this.finishStatus = 1;
    },
    rollback() {
      this.$router.push("/dpia/service");
    },
    returnChapter() {
      let _this = this;
      this.$confirm({
        title: this.$t("user.verification-code.returnchapterconform"),
        okText: this.$t("user.email.required1111"),
        cancelText: this.$t("user.email.required11"),
        async onOk() {
          let res = await dpiaChangeState({
            Id: _this.id,
            DpiaStatus: 2,
          });
          if (res.code === 1) {
            let record = _this.$route.query;
            const res = await isWithdraw({ Id: record.Id });
            if (res.data == 0) {
              _this.$message.error("不可评估");
              return;
            }
            // DCO评估
            _this.$router.push({
              path: "/dpia/onequestion/estimate",
              query: {
                ..._this.$route.query,
                id: record.Id,
                DpiaCreateUserId: record.DpiaCreateUserId,
                DpiaChangeDcoId: record.DpiaChangeDcoId || "",
                DpiaId: record.DpiaId,
                ChangeCommit: record.Role ? record.Role.CHANGE : record.CHANGE,
                ifDco: record.Role ? record.Role.DCO : record.ifDco,
              },
            });
            localStorage.setItem("ifchaning", true);
          }
        },
      });
    },
  },
};
</script>
  
<style lang="less" scoped>
/deep/ .ant-card-body {
  // display: flex;

  .buttomm {
    width: 100%;
  }

  .card-box {
    font-size: 15.5px;
    display: flex;
  }

  .card-left {
    /*rectangle copy 4备份 87*/
    margin: 20px 30px 20px 20px;
    color: #444e84;
    left: 339px;
    top: 287px;
    width: 388px;
    height: 428px;
    opacity: 0.67;
    border-radius: 2px;
    background: #f7faff;

    ul {
      margin-top: 10px;
    }

    ul li {
      padding: 3px;
    }
  }

  .left-title {
    color: #050c34;
    width: 100%;
    line-height: 40px;
    padding: 0 10px;
    padding-left: 20px;
    background: #e7f0ff;
    border-bottom: 1px solid #ddd;
  }

  .card-right {
    margin: 20px 20px 20px 20px;
  }

  p {
    color: #000;
  }
}

.tags {
  left: 298px;
  top: 288px;
  width: 6px;
  height: 14px;
  opacity: 1;
  border-radius: 2px;
  background: rgba(0, 80, 247, 1);
}

.ant-card {
  overflow: auto;
  height: auto;
}

.card-right {
  margin: 30px 30px 30px 60px;
}
</style>